﻿var initSelect = function (context, target, preview, previewWidth, previewHeight) {

    var ctx = context || $(document);
    //Get the button of the form of the context
    var button = $('button', ctx).attr('disabled', true);
    //Get the form of the context
    var form = $('form', ctx);
    // preview image
    var preview = preview;
    var target = target;

    // Create variables (in this scope) to hold the API and image size
    var jcrop_api = null, boundx, boundy;

    var updatePreview = function (c) {
        if (parseInt(c.w) > 0) {
            $('#Y', ctx).val(Math.round(c.y));
            $('#X', ctx).val(Math.round(c.x));
            $('#Width', ctx).val(Math.round(c.w));
            $('#Height', ctx).val(Math.round(c.h));
            var rx = previewWidth / c.w;
            var ry = previewHeight / c.h;
            preview.css({
                width: Math.round(rx * boundx) + 'px',
                height: Math.round(ry * boundy) + 'px',
                marginLeft: '-' + Math.round(rx * c.x) + 'px',
                marginTop: '-' + Math.round(ry * c.y) + 'px'
            });
        }
    };

    //Get the preview image and set the onload event handler
    preview.load(function (evt) {
        preview.css({
            width: previewWidth + 'px',
            height: 'auto',
            marginLeft: 'auto',
            marginTop: 'auto'
        });

        $('#Y', ctx).val(0);
        $('#X', ctx).val(0);

        if (jcrop_api == null || jcrop_api == undefined) {
            target.Jcrop({
                onChange: updatePreview,
                onSelect: updatePreview,
                aspectRatio: 1,
                boxWidth: 500,
                boxHeight: 500
            }, function () {
                // Use the API to get the real image size
                var bounds = this.getBounds();
                boundx = bounds[0];
                boundy = bounds[1];
                jcrop_api = this;
                saveRealSize(bounds);
            });
        }
        else {
            var src = preview.attr('src');
            jcrop_api.setImage(src,
            function () {
                var bounds = jcrop_api.getBounds();
                boundx = bounds[0];
                boundy = bounds[1];
                saveRealSize(bounds);
            });
            button.attr("disabled", false);
        }
    });

    var saveRealSize = function (bounds) {
        $('#Y', ctx).val(0);
        $('#X', ctx).val(0);
        $('#Width', ctx).val(Math.round(bounds[0]));
        $('#Height', ctx).val(Math.round(bounds[1]));
    };

    //What happens if the File changes?
    $('#File', ctx).change(function (evt) {
        if (evt.target.files === undefined) {
            //alert("Your browser doesn't support FileApi");
            return filePreview(evt.target.value);
        }

        var fileSize = getFileSize(evt);
        //alert(fileSize + ' Mb');

        var f = evt.target.files[0];
        if (!f.type.match('image.*')) {
            alert("The selected file does not appear to be an image.");
            if (jcrop_api != null && jcrop_api != undefined) {
                jcrop_api.setImage("");
            }
            button.attr("disabled", true);
            return;
        }

        var reader = new FileReader();
        reader.onload = function (e) {
            var src = e.target.result;
            target.attr('src', src);
            preview.attr('src', src);
        };
        reader.readAsDataURL(f);
    });

    //gets file size in Mb
    var getFileSize = function (evt) {
        var browserInfo = navigator.userAgent.toLowerCase();
        if (browserInfo.indexOf("msie") > -1) {
            /* IE */
            var filepath = evt.target.value;
            //alert(filepath + " Test ");
            var myFSO = new ActiveXObject("Scripting.FileSystemObject");
            var thefile = myFSO.getFile(filepath);
            return thefile.size / 1024 / 1024;
        } else {
            /* Other */
            var file = evt.target.files[0];
            return file.size / 1024 / 1024;
        }
    };

    //Fallback for Browsers with no FileAPI
    var filePreview = function (path) {
        window.callback = function () { };
        $('body').append('<iframe id="preview-iframe" onload="callback();" name="preview-iframe" style="display:none"></iframe>');
        var action = $('form', ctx).attr('target', 'preview-iframe').attr('action');
        form.attr('action', '/Image/UploadImagePartial');
        window.callback = function () {
            button.attr('disabled', false);
            //var result = $('#preview-iframe').contents().find('img').attr('src');
            target.attr('src', path);
            preview.attr('src', path); //result);
            $('#preview-iframe').remove();
        };
        form.submit().attr('action', action).attr('target', '');
    };

    form.submit(function () {
        button.attr('disabled', true).text('Please wait ...');
    });
};